// pages/Match/Match.js
const app = getApp()
import http from '../../utils/request.js'
import api from '../../utils/api.js'
import * as echarts from '../../ec-canvas/echarts';

function dur(a) {
  if (isNaN(a)) {
    return '--';
  }
  var hour = parseInt(a / 3600)
  if (hour >= 1) {
    hour = hour + ":"
  } else {
    hour = ""
  }
  var min = parseInt(a % 3600 / 60)
  if (min < 10) {
    min = "0" + min + ":"
  } else {
    min = min + ":"
  }
  var sec = parseInt(a % 60)
  if (sec < 10) {
    sec = "0" + sec
  } else {
    sec = sec
  }
  return hour + min + sec
}

function setOption(chart, legend, xAxis, series, last) {
  const option = {
    legend: {
      data: legend
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: [{
      type: 'category',
      boundaryGap: false,
      data: xAxis,
      axisLabel: {
        formatter(value, index) {
          value = parseInt(value)
          return dur(value);
        }
      }
    }],
    yAxis: [{
      type: 'value'
    }],
    series: series
  };
  chart.setOption(option);
}
Page({

  options: {
    styleIsolation: 'apply-shared'
  },
  /**
   * 页面的初始数据
   */
  data: {
    match: {},
    ec: {
      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
    },
    isLoaded: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let {
      matchId
    } = options
    wx.setNavigationBarTitle({
      title: '比赛 ' + matchId
    })
    //获取比赛信息
    this.getMatch(matchId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.ecComponent = this.selectComponent('#mychart-dom-bar');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  getMatch(matchId) {
    //展示加载中
    wx.showLoading({
      title: '加载中'
    })
    http.get(api.matchDetail + matchId)
      .then(result => {
        wx.hideLoading()
        let data = result.data.data;
        let match = data.match;
        this.getProcess(match.id)
        let time;
        let endTime = new Date(match.endTime).getTime() / 1000;
        this.setData({
          endTime,
          gameMode: match.gameMode,
          playbackTime: (match.gameTime / 60).toFixed(0)
        })
        let banList = [];
        let pickList = [];
        for (let item of data.banPickList) {
          if (item.pick) {
            pickList.push(item);
          } else {
            banList.push(item)
          }
        }
        for (let player of data.players) {
          let id = player.id;
          // 最终物品
          let items = data.playerItems[id] || [];
          let itemDict = {};
          for (let item of items) {
            itemDict[item.index] = item;
          }
          player.items = itemDict;
          // 本场表现
          let performance = data.performances[id];
          Object.assign(player, performance)
          let goldPerMin = performance.gpm.toFixed(0);
          let xpPerMin = performance.xpm.toFixed(0);
          player.goldPerMin = parseInt(goldPerMin);
          player.xpPerMin = parseInt(xpPerMin);
          // 技能选择
          let abilities = data.abilities[id];
          player.abilities = abilities || [];
        }

        this.setData({
          banList,
          pickList,
          performances: data.performances,
          match: data.match,
          players: data.players
        })
      })
  },
  getProcess(matchId) {
    http.get(api.process + '?matchId=' + matchId).then(response => {
      const data = response.data.data
      console.log(data)
      this.setData({
        process: data
      })

      let xps = {
        'RADIANT': {},
        'DIRE': {}
      }
      let golds = {
        'RADIANT': {},
        'DIRE': {}
      }
      for (let p of data) {
        let time = p.time
        let xp = xps[p.team.name][time] || 0
        xp += p.xp
        xps[p.team.name][time] = xp

        let gold = golds[p.team.name][time] || 0
        gold += (p.gold - p.goldLostToDeath - p.goldSpentOnBuybacks)
        golds[p.team.name][time] = gold
      }

      let xpToal = []
      let goldToal = []
      let xAxis = []
      for (let time in xps['RADIANT']) {
        let radiantXp = xps['RADIANT'][time]
        let direXp = xps['DIRE'][time]
        let radiantGold = golds['RADIANT'][time]
        let direGold = golds['DIRE'][time]
        xpToal.push(radiantXp - direXp)
        goldToal.push(radiantGold - direGold)
        xAxis.push(time)
      }

      let series = [{
        name: '经济',
        type: 'line',
        stack: '总量',
        data: goldToal,
        symbol: 'none'
      }, {
        name: '经验',
        type: 'line',
        stack: '总量',
        data: xpToal,
        symbol: 'none'
      }]
      this.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: 200,
          devicePixelRatio: dpr // new
        });
        setOption(chart, ['经济', '经验'], xAxis, series, this.data.match.gameTime);

        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart = chart;

        this.setData({
          isLoaded: true
        });

        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    })
  }
})